class SessionsController < ApplicationController
  
  def authorize      
  end

  def relogin_check
  end
  
  def close_browser_remind
    session[:close_browser_remind] = true
    render :status => 200, :text => 'success'
  end
  
  def new 
    @http_referer = params[:http_referer].present? ? params[:http_referer] : request.referer
    @http_referer = nil if @http_referer.try(:match,'/sessions/new') or @http_referer.try(:match,'/admins/new')
    @session = flash[:session].present? ? {
      :enterprise_name => flash[:session][:enterprise_name],
      :mobile => flash[:session][:mobile],
      :remember_me => flash[:session][:remember_me]
    } : {
      :enterprise_name => cookies.signed[:enterprise_name]
    }
    def @session.enterprise_name
      self[:enterprise_name]      
    end
    def @session.mobile   
      self[:mobile]   
    end
    def @session.password
    end
    def @session.remember_me
      self[:remember_me] || 'no'
    end
  end
  
  def create
    @http_referer = params[:http_referer] if params[:http_referer].present?          
    user = User.authenticate(params[:session])
    if user.present?
      session[:current_user_id] = user.id
      cookies.signed[:enterprise_name] = {
        :value => user.enterprise.name,
        :expires => 5.days.from_now
      } 
      # remember me      
      if params[:session][:remember_me] == 'yes'
        cookies.signed[:user_id] = {
          :value => current_user_id.to_s,
          :expires => 10.years.from_now
        }
        cookies.signed[:user_security_key] = {
          :value => current_user.security_key_in_cookies,
          :expires => 10.years.from_now
        } 
      else
        clear_login_info_from_cookies
      end
      current_user.reset_login_token!
      cookies.signed[:login_token] = {
        :value => current_user.login_token,
        :expires => 10.years.from_now
      } 
      redirect_to(@http_referer || root_url)
    else
      clear_login_info_from_cookies
      flash[:error] = '企业名称、手机号和密码不匹配哦，再仔细想想。如果忘记了请联系管理员解决'
      flash[:session] = params[:session]
      redirect_to :action => :new
    end
  end
  
  def destroy
    session.delete :current_user_id
    clear_login_info_from_cookies
    redirect_to new_session_url(:http_referer => root_url )
  end

  private
  def clear_login_info_from_cookies
    cookies.delete :user_id
    cookies.delete :user_security_key
  end  
end
